package com.hw.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.hw.springcloud.entities.CommonResult;
import com.hw.springcloud.entities.Payment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @Classname: OrderController
 * @Description: 描述
 * @Date: 2021/12/16
 * @Author: HuWei
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    private static String SERVER_URL = "http://cloudalibaba-nacos-provide-payment";

    @Resource
    private RestTemplate restTemplate;

    /**
     * fallback只处理java运行时的异常
     * blockHandler只处理Sentinel管理的阈值
     * 当fallback和blockHandler同时出现会优先使用blockHandler内的代码处理问题
     * exceptionsToIgnore表示会忽略标注的类出现的问题
     *
     */
    @GetMapping("/getById/{id}")
    //@SentinelResource(value = "getById",fallback = "fallBackHandle")
    //@SentinelResource(value = "getById",blockHandler = "blockHandle")
    @SentinelResource(value = "getById",fallback = "fallBackHandle",blockHandler = "blockHandle",exceptionsToIgnore = {IllegalArgumentException.class})
    public CommonResult<Payment> getById(@PathVariable("id")Long id){
        CommonResult<Payment> getById = restTemplate.getForObject(SERVER_URL + "/payment/getById/" + id, CommonResult.class, id);
        if(id == 5){
            throw new IllegalArgumentException("非法参数异常");
        }else if (getById.getData() == null){
            throw new NullPointerException("空异常");
        }
        return getById;
    }

    public CommonResult fallBackHandle(@PathVariable("id")Long id,Throwable throwable){
        return new CommonResult(500,throwable.getMessage(),id);
    }

    public CommonResult blockHandle(@PathVariable("id")Long id, BlockException blockException){
        return new CommonResult(500,blockException.getClass().getCanonicalName(),id);
    }
}